#include "FBXWriter.hpp"
#include <iostream>
#include "common/logger.h"
#include "fbxw/fbxw.hpp"

namespace  AMCAX::Exchange {

    Dtk_ErrorStatus FBXWriter::WriteInit(Dtk_string dumpFile, const Dtk_string& outputFile)
    {
        return WriteInit(dumpFile, outputFile, 0);
    }

    Dtk_ErrorStatus FBXWriter::WriteInit(Dtk_string dumpFile, const Dtk_string& outputFile, int option)
    {
        m_outputFileName = outputFile;
        std::cout << "Output file is : " << m_outputFileName << std::endl;

        m_backupLocale = std::locale::global(std::locale("C")); // 禁用所有本地化格式, 否则输出数字千位符为，会导致非法
        
        DtkErrorStatus status = dtkNoError;
        // First we initialize writing with name of files and protection fonction if needed (3rd parameter)
        m_FW = new Dtk_FBXWriter( m_outputFileName, status );

        if( status != dtkNoError )
        {
            std::cout << "error : " << dtkTypeError( status ).c_str() << std::endl;
            return status;
        }

        Dtk_bool useless;
        m_FW->OpenInstance( "RootNode", -1, useless );

        return dtkNoError;
    }

    Dtk_ErrorStatus FBXWriter::WriteEnd()
    {
        m_FW->CloseLastInstance();

        delete m_FW;
        m_FW = nullptr;

        std::locale::global(m_backupLocale); // 恢复全局locale

        return Dtk_ErrorStatus::dtkNoError;
    }

    void FBXWriter::WriteMesh(Dtk_MeshPtr& inMeshToWrite, Dtk_tab<Dtk_ID>& outIds)
    {
        Dtk_bool isNewNode;
        auto strID = std::to_string(inMeshToWrite->get_id());
        m_FW->OpenInstance( strID.c_str(), -1, isNewNode); // Giving ID 1

		m_FW->WriteMesh( inMeshToWrite );

		m_FW->CloseLastInstance();

    }

}
